//
//  TCMicroAppStore.swift
//  TinyUI
//
//  Created by 徐涛 on 2020/3/25.
//  Copyright © 2020 葛晓良. All rights reserved.
//

import UIKit
import TinyResource
import TinyUI
import TinyDataBase
let tcomponent_microAppStore_config_name = "MicroAppStore"
let ScreenWidth  = UIScreen.main.bounds.width

enum TCMicroAppStoreState{
    case nomal  //浏览
    case edit  //编辑状态
    case show //展示
    
}

enum TCMicroAppStoreSectionType{
    case myApp  //我的App
    case myAppOverstep  //超出最大限制的我的App
    case other  //其他分组  （后续根据业务可添加）
    
}

class TCMicroAppStore: Div,UIComponentElement {
    //****cell header footer
    private let iconCellId = "IconCellId"
    private let myAppCellId = "MyAppCellId"
    private let headViewId = "headViewId"
    private let footViewId = "footViewId"
    
    private let groupID="groupId"//其他App分组名称
    private let groupApps="data"//其他App分组里包含的名称
    
    
    //*****参数****
    private let headerHeight:CGFloat = 30
    private let layout = UICollectionViewFlowLayout.init()
    private let perLineCellCount=5
    private var cellHeight=96
    private var myGeted=false
    private var allGeted=false
    var dependenceParam:NSDictionary=NSDictionary.init()
    var kThemeChangeNotificationKey="ThemeChangeNotificationKey"
    //******数据******
    private var myAppState:TCMicroAppStoreState=TCMicroAppStoreState.nomal// 状态  编辑 非编辑
    
    private var dateSource:Dictionary<String,Any> = Dictionary<String,Any>.init()//数据分my other
    
    private var originAllAppDateArr:NSMutableArray = NSMutableArray.init()//存放未被服务微应用 下架 过滤的All微应用
    
    private var originMyAppDateArr:NSMutableArray = NSMutableArray.init()//存放未被服务微应用 下架 过滤的我的微应用
    
    
    
    let resource: TinyMicroAppProtocol&Resource = Resource.shareInstance()
    
    let dataStoreHelper:MicroDataStoreHelper = MicroDataStoreHelper.init()
    //*******attr******
    private var dataPath:String = "app.json"
    private var dataKey:String = "allApp.dataInfos"
    
    private var myDataPath:String = "app.json"
    private var myDataKey:String = "myApp.dataInfos"
    
    private var maxCount:Int = 0 //我的应用中最大限制数量
    private var minCount:Int = 0 //我的应用中不可再删除的数量
    
    private var excludeList:Array = Array<String>.init();//存放不显示的微应用Key数组
    
    private var addListener:Bool = false//点击微应用true打开抛出数据 false打开微应用
    
    public var dependencePath:String=String.init()//dependence的路径
    //******手势*******
    private lazy var longPressGesture: UILongPressGestureRecognizer = {
        return UILongPressGestureRecognizer.init(target:self, action: #selector(longPressAction(_:)))
    }()
    
    
    //    private var user_token: String?
    lazy var errorV: UIView = {
        let carry:UIView = UIView.init()
        carry.frame=CGRect(x: 0, y: 0, width: 172, height: 158)
        let imagV = UIImageView.init()
        imagV.frame=CGRect(x: 0, y: 0, width: 172, height: 128)
        imagV.image=UIImage(named:"MicroAppStore.bundle/network_error")
        carry.addSubview(imagV)
        
        let tipLbl:UILabel=UILabel.init()
        tipLbl.frame=CGRect(x: 0, y: 128, width: 172, height: 30)
        tipLbl.textAlignment=NSTextAlignment.center;
        tipLbl.textColor=UIColor.tyColor(withHex:"#d8d8d8")
        tipLbl.text="网络出错，请检查网络"
        tipLbl.font=UIFont.systemFont(ofSize: 13)
        carry.addSubview(tipLbl)
        self.addSubview(carry)
        carry.isHidden=true
        return carry
    }()
    
    lazy var appCollectionView: UICollectionView = {
        layout.minimumInteritemSpacing=0
        layout.minimumLineSpacing=0
        
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        let collection = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
        collection.backgroundColor=UIColor.clear
        collection.delegate=self;
        collection.dataSource=self;
        
        //注册cell
        collection.register(MyAppCell.classForCoder(), forCellWithReuseIdentifier: myAppCellId)
        collection.register(MicroAppCell.classForCoder(), forCellWithReuseIdentifier:iconCellId)
        
        //注册head
        collection.register(MicroAppHeadView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headViewId)
        //注册footView
        collection.register(MicroAddAppView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: footViewId)
        return collection;
    }()
    
    // 组件的名字
    func getName() -> String {
        return tcomponent_microAppStore_config_name
    }
    
    // 组件布局属性，由运行时决定
    func getFrameAttrbutes() -> Dictionary<String, String> {
        var res = Dictionary<String, String>()
        if let attributes = self.context.element.attributes as? Dictionary<String, String> {
            res.merge(attributes) { (_, new) -> String in new }
        }
        return res
    }
    
    
    // 设置属性
    func setParam(_ param: String, value object: Any) {
        if param == "allApps" {
            self.dateSource.removeValue(forKey: "group")
            self.compilerAllAppList(object as? [Any])
            self.synchronizationDate();
            allGeted=true
            reloadsynchron()
        }
        if param == "ownerApps" {
            self.dateSource.removeValue(forKey: "my")
            self.compilerOwnerAppList(object as? [Any])
            self.synchronizationDate();
            myGeted=true
            reloadsynchron()
        }
        
        if let dict = object as? Dictionary<String, String>, dict.count > 0 {
            if dict["dependenciesUri"] != nil {
                self.dependencePath = dict["dependenciesUri"]!
            }
        }
        if param == "" {
            dependenceParam=object as? NSDictionary ?? NSDictionary.init()
            if let addList = dependenceParam["addListener"] as? String{
                if addList == "true" {
                    addListener=true
                }else{
                    addListener=false
                }
            }
        }
    }
    
    func reloadsynchron() {
        if myGeted&&allGeted {
            self.appCollectionView.reloadData();
        }
    }
    
    // 构造函数
    required   init(element: Element) {
        super.init(element: element)
        self.componentAttributeChanged()
        self.backgroundColor=UIColor.clear
        self.addSubview(self.appCollectionView)
        
        self.dateSource["my"] = NSMutableArray.init()
        self.dateSource["group"] = NSMutableArray.init()
        
        if let attDataPath:String = self.context.element.attributes["dataPath"] as? String {
            if !attDataPath.contains("{{") {
                self.dataPath = attDataPath
            }
        }
        if let attDataKey:String = self.context.element.attributes["dataKey"] as? String {
            if !attDataKey.contains("{{") {
                self.dataKey = attDataKey
            }
        }
        if let attMyDataPath:String = self.context.element.attributes["myDataPath"] as? String {
            if !attMyDataPath.contains("{{") {
                self.myDataPath = attMyDataPath
            }
        }
        if let attMyDataKey:String = self.context.element.attributes["myDataKey"] as? String {
            if !attMyDataKey.contains("{{") {
                self.myDataKey = attMyDataKey
            }
        }
        if let attMaxCount:String = self.context.element.attributes["maxCount"] as? String {
            if !attMaxCount.contains("{{") {
                self.maxCount = Int(attMaxCount) ?? 0
            }
        }
        if let attMinCount:String = self.context.element.attributes["minCount"] as? String {
            if !attMinCount.contains("{{") {
                self.minCount = Int(attMinCount) ?? 0
            }
        }
        listenCompare();
        
        NotificationCenter.default.addObserver(self, selector: #selector(themeChangeMethod(_:)), name: NSNotification.Name(rawValue: kThemeChangeNotificationKey), object: nil);
        //        //************
        //        self.readDataSource();
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.appCollectionView.frame = self.bounds
    }
    
    @objc func themeChangeMethod(_ notification: Notification) {
        dataStoreHelper.changeThemeIconForCell(dataSource: self.dateSource)
        self.readDataSource();
    }
    
    //MARK:-deinit
    deinit {
        NotificationCenter.default.removeObserver(self);
        //        print("appStore deinit")
        //        resource.removeObserver(self, forKeyPath: "token")
    }
}


extension TCMicroAppStore:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        let sectionNum = 1 + (((dateSource["my"] as? Array<Any>)?.count ?? 0)>maxCount ? 1:0 ) + ((dateSource["group"] as? Array<Any>)?.count ?? 0)
        return sectionNum
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let sectionType = self.sectionType(section: section)
        let isOverMax:Bool = self.isOverMaxCount() //是否有超越maxCount的
        if sectionType==TCMicroAppStoreSectionType.myApp {
            if self.myAppState==TCMicroAppStoreState.nomal {
                return ((dateSource["my"] as? Array<Any>)?.count ?? 0) > 0 ?1:0
            }else if self.myAppState == TCMicroAppStoreState.show{
                return (isOverMax ? maxCount : ((dateSource["my"] as? Array<Any>)?.count ?? 0))+1
            }
            return (isOverMax ? maxCount : ((dateSource["my"] as? Array<Any>)?.count ?? 0))
            
        }else if sectionType==TCMicroAppStoreSectionType.myAppOverstep{
            guard let my = dateSource["my"] as? Array<Any> else {
                return 0
            }
            let overNum = my.count - maxCount;
            return (overNum>0) ? overNum : 0;
        }else{
            let gap = isOverMax ? 2:1
            guard let group = dateSource["group"] as? Array<Any> else {
                return 0
            }
            guard let group_obj = group[section-gap] as? Dictionary<String,Any>  else {
                return 0
            }
            guard let group_obj_obj = group_obj[groupApps] as? Array<Any> else {
                return 0
            }
            return group_obj_obj.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let sectionType = self.sectionType(section: indexPath.section)
        let isOverMax:Bool = self.isOverMaxCount() //是否有超越maxCount的
        if sectionType==TCMicroAppStoreSectionType.myApp {
            if self.myAppState==TCMicroAppStoreState.nomal {//浏览状态
                if indexPath.row==0 {//我的应用
                    let cell:MyAppCell = collectionView.dequeueReusableCell(withReuseIdentifier:myAppCellId, for: indexPath) as! MyAppCell
                    cell.configWithParam(param:(dateSource["my"] as! Array<MicroAppModels>), limit: maxCount, dependence: dependenceParam)
                    return cell
                }
            }else{
                let countNum = isOverMax ? maxCount : (dateSource["my"] as! Array<Any>).count
                if indexPath.row < countNum{
                    let model=(dateSource["my"] as! Array<Any>)[indexPath.row] as! MicroAppModels
                    let cell:MicroAppCell = collectionView.dequeueReusableCell(withReuseIdentifier:iconCellId, for: indexPath) as! MicroAppCell
                    cell.configWithParams(model:model, state: myAppState, isMyApp: true, myApps:nil ,dependence: dependenceParam)
                    return cell
                }else{
                    let cell:MicroAppCell = collectionView.dequeueReusableCell(withReuseIdentifier:iconCellId, for: indexPath) as! MicroAppCell
                    cell.configCollapse(dependence: dependenceParam,dependencePath: dependencePath)
                    return cell
                }
            }
        }else if sectionType==TCMicroAppStoreSectionType.myAppOverstep {
            let overNum = (dateSource["my"] as! Array<Any>).count - maxCount
            if indexPath.row < overNum{
                let model=(dateSource["my"] as! Array<Any>)[indexPath.row + maxCount] as! MicroAppModels
                let cell:MicroAppCell = collectionView.dequeueReusableCell(withReuseIdentifier:iconCellId, for: indexPath) as! MicroAppCell
                cell.configWithParams(model:model, state: myAppState, isMyApp: true, myApps:nil,dependence: dependenceParam)
                return cell
            }
        }
        let gap = isOverMax ? 2:1
        let agroupDic:Dictionary<String,Any> = (dateSource["group"] as! Array<Any>)[indexPath.section-gap] as! Dictionary<String,Any>
        let agroupArr=agroupDic[groupApps] as! Array<Any>
        let model=agroupArr[indexPath.row] as! MicroAppModels
        let cell:MicroAppCell = collectionView.dequeueReusableCell(withReuseIdentifier:iconCellId, for: indexPath) as! MicroAppCell
        if  self.myAppState==TCMicroAppStoreState.edit {
            self.isInMyAPP(model: model)
        }
        cell.configWithParams(model:model, state: myAppState, isMyApp: false,  myApps:(self.dateSource["my"] as?  NSMutableArray ?? nil),dependence: dependenceParam)
        
        
        return cell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionType = self.sectionType(section: indexPath.section)
        let isOverMax:Bool = self.isOverMaxCount() //是否有超越maxCount的
        if sectionType==TCMicroAppStoreSectionType.myApp {
            if myAppState == TCMicroAppStoreState.nomal {
                if indexPath.row==0 {
                    return  CGSize(width: self.bounds.width, height: 86)
                }
            }else{
                let countNum = isOverMax ? maxCount : (dateSource["my"] as! Array<Any>).count
                if indexPath.row < countNum {
                    let cellWidth:CGFloat = CGFloat((self.bounds.size.width)/5.0)
                    return    CGSize(width: cellWidth, height:CGFloat(cellHeight))
                }
            }
            
        }else if sectionType==TCMicroAppStoreSectionType.myAppOverstep{
            let overNum = (dateSource["my"] as! Array<Any>).count - maxCount
            if indexPath.row < overNum{
                let cellWidth:CGFloat = CGFloat((self.bounds.size.width)/5.0)
                return    CGSize(width: cellWidth, height:CGFloat(cellHeight))
            }
        }
        
        let cellWidth:CGFloat = CGFloat((self.bounds.size.width)/5.0)
        return    CGSize(width: cellWidth, height:CGFloat(cellHeight))
        
    }
    
    
    
    func getSection(key:String?=nil) -> Int {
        var ic=0;
        let arr=dateSource["group"] as? Array<Any> ?? Array.init()
        for i in 0..<arr.count{
            let agroupDic = arr[i] as? Dictionary<String,Any>
            let agroupArr=agroupDic?[groupApps] as! Array<Any>
            for item in agroupArr {
                let chooseModel:MicroAppModels=item as! MicroAppModels
                if chooseModel.appKey == key{
                    ic=i
                    return ic
                }
            }
        }
        
        return 0;
    }
    
    
    //MARK:-select-cell
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let sectionType = self.sectionType(section: indexPath.section)
        let isOverMax:Bool = self.isOverMaxCount() //是否有超越maxCount的
        if sectionType==TCMicroAppStoreSectionType.myApp {
            if self.myAppState == TCMicroAppStoreState.nomal {//未编辑情况下点击
                if indexPath.row==0 {
                    changeShowState()
                }
            }else {
                let countNum = self.isOverMaxCount() ? maxCount : (dateSource["my"] as! Array<Any>).count
                if  indexPath.row < countNum {
                    let chooseModel:MicroAppModels=(dateSource["my"] as!  NSMutableArray)[indexPath.row] as! MicroAppModels
                    if  myAppState == TCMicroAppStoreState.show {
                        if ((dependenceParam["item-anim"] as? String ) == "true" ) {
                            let selectCell:MicroAppCell = collectionView.cellForItem(at: indexPath) as! MicroAppCell
                            selectCell.imageShake()
                        }
                        guard (chooseModel.appKey != nil) else{return}
                        openMicroApp(key: chooseModel.appKey!,sourceDic: chooseModel.sourceDic)
                    }
                    if myAppState == TCMicroAppStoreState.edit{
                        
                        if  (self.dateSource["my"] as!  NSMutableArray).count <= self.minCount{
                            let script:JSValue?=self.context.element.eventDictinoary["deleteLimit"] as? JSValue
                            if script != nil {
                                script?.call(withArguments: [String(format: "%d", minCount)] )
                            }
                            return;
                        }
                        guard (chooseModel.appKey != nil) else{return}//todo 修改
                        self.removeMyOriginItem(key:chooseModel.appKey!)//源数据 删除
                        //*******任务中心用法
                        (self.dateSource["my"] as!  NSMutableArray).removeObject(at: indexPath.row)
                        
                        self.minusMicro(model: chooseModel)
                        DispatchQueue.main.asyncAfter(deadline: .now() + Double(0.2), execute:{
                            UIView.performWithoutAnimation {
                                collectionView.reloadData()
                                self.alertSom(message: "取消成功")
                            }
                        })
                        //                        DispatchQueue.main.asyncAfter(deadline: .now() + Double(0.2), execute:{
                        //                            var sect=self.getSection(key: chooseModel.appKey)
                        //                            collectionView.reloadSections(NSIndexSet.init(index: 0) as IndexSet)
                        //                            collectionView.reloadSections(NSIndexSet.init(index: sect+1) as IndexSet)
                        //                            self.alertSom(message: "取消成功")
                        //                        })
                    }
                    
                }else {
                    if myAppState == TCMicroAppStoreState.show{
                        changeShowState()
                    }
                }
            }
        }else if sectionType==TCMicroAppStoreSectionType.myAppOverstep{
            let overNum = (dateSource["my"] as! Array<Any>).count - maxCount
            if  indexPath.row < overNum {
                let chooseModel:MicroAppModels=(dateSource["my"] as!  NSMutableArray)[indexPath.row + maxCount] as! MicroAppModels
                if  myAppState == TCMicroAppStoreState.show || myAppState == TCMicroAppStoreState.nomal {
                    if ((dependenceParam["item-anim"] as? String ) == "true" ) {
                        let selectCell:MicroAppCell = collectionView.cellForItem(at: indexPath) as! MicroAppCell
                        selectCell.imageShake()
                    }
                    guard (chooseModel.appKey != nil) else{return}
                    openMicroApp(key: chooseModel.appKey!,sourceDic: chooseModel.sourceDic)
                }
                if myAppState == TCMicroAppStoreState.edit{
                    
                    guard (chooseModel.appKey != nil) else{return}
                    //todo
                    self.removeMyOriginItem(key:chooseModel.appKey!)//源数据 删除
                    //*******任务中心用法
                    (self.dateSource["my"] as!  NSMutableArray).removeObject(at: indexPath.row+maxCount)
                    
                    self.minusMicro(model: chooseModel)
                    
                    DispatchQueue.main.asyncAfter(deadline: .now() + Double(0.2), execute:{
                        UIView.performWithoutAnimation {
                            collectionView.reloadData()
                            self.alertSom(message: "取消成功")
                        }
                    })
                }
            }
        }else {
            let gap = isOverMax ? 2:1
            let agroupDic:Dictionary<String,Any> = (dateSource["group"] as! Array<Any>)[indexPath.section-gap] as! Dictionary<String,Any>
            let agroupArr=agroupDic[groupApps] as! Array<Any>
            let chooseModel:MicroAppModels=agroupArr[indexPath.row] as! MicroAppModels
            if self.myAppState == TCMicroAppStoreState.edit  {
                //取出otherApp中选择的APP 如其Id已存在则提示已经加过
                if isInMyAPP(model: chooseModel) {
                    NSLog("已经添加到我的APP中")
                    return
                }
                //***************直接在本地操作修改
                guard (chooseModel.appKey != nil) else{return}
                
                let myCount = (self.dateSource["my"] as! Array<Any>).count
                let cellXIdx:Int = isOverMax ? myCount-maxCount+1 : myCount+1
                let head1Height:CGFloat=70
                let head2Height:CGFloat=23
                var pX:CGPoint=CGPoint()
                if cellXIdx%5 == 1 {//需要换行
                    var y:CGFloat=0.0;
                    if isOverMax {
                        let line = (maxCount%5 == 0) ? (maxCount/5) : (maxCount/5+1)
                        y = CGFloat((cellXIdx/5) * self.cellHeight)+CGFloat(line * self.cellHeight)+CGFloat(head2Height)+CGFloat(head1Height)
                    }else{
                        y = CGFloat((cellXIdx/5) * self.cellHeight)+CGFloat(head1Height)
                    }
                    pX=CGPoint(x: 0, y: y)
                }else{
                    let x = (CGFloat((cellXIdx-1)%5) * (self.bounds.size.width)/5)
                    var y:CGFloat=0.0;
                    if isOverMax {
                        let line = (maxCount%5 == 0) ? (maxCount/5) : (maxCount/5+1)
                        y = CGFloat(((cellXIdx-1)/5) * self.cellHeight)+CGFloat(line * self.cellHeight)+CGFloat(head2Height)+CGFloat(head1Height)
                    }else{
                        y = CGFloat((cellXIdx-1)/5) * CGFloat(self.cellHeight)+head1Height
                    }
                    pX=CGPoint(x: x, y: y)
                }
                var aimPoint=CGPoint(x: 0, y: 0)
                let p: CGPoint = collectionView.contentOffset//myApp超出屏幕后
                
                if p.y < (pX.y+CGFloat(self.cellHeight)){
                    aimPoint=pX
                }else{
                    aimPoint=p
                }
                
                aimPoint=CGPoint(x: aimPoint.x+0.5*(self.bounds.size.width)/5, y: aimPoint.y+CGFloat(0.5 * Double(self.cellHeight)))
                let cell:MicroAppCell=collectionView.cellForItem(at: indexPath) as! MicroAppCell
                cell.anim.animateParabola(startRect: cell.frame,begView:cell,  superView: collectionView, lastPoint: aimPoint, startToEndSpacePercentage: 4, animationValue: 5)
                chooseModel.isInMy=true
                //******任务中心用法****后面测试
                self.addMicro(model: chooseModel)
                collectionView.allowsSelection=false
                DispatchQueue.main.asyncAfter(deadline: .now() + Double(cell.animTime), execute:{
                    UIView.performWithoutAnimation {
                        collectionView.reloadData()
                        collectionView.allowsSelection=true
                        self.alertSom(message: "添加成功")
                    }
                })
            }else{
                if ((dependenceParam["item-anim"] as? String ) == "true" ) {
                    let selectCell:MicroAppCell = collectionView.cellForItem(at: indexPath) as! MicroAppCell
                    selectCell.imageShake()
                }
                guard (chooseModel.appKey != nil) else {
                    return
                }
                dataStoreHelper.checkOpenAppInStore(model: chooseModel)
                openMicroApp(key: chooseModel.appKey!,sourceDic: chooseModel.sourceDic)
            }
        }
    }
    
    func alertSom(message:String)  {
        WindowHUD.shared()?.showDetail(message, delay: 1)
    }
    
    
    //MARK:-header footer
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableview:UICollectionReusableView!
        let sectionType = self.sectionType(section:indexPath.section)
        let isOverMax:Bool = self.isOverMaxCount() //是否有超越maxCount的
        let gap = isOverMax ? 2:1
        if kind == UICollectionView.elementKindSectionHeader{
            //            let isOtherFirst:Bool = (sectionType==TCMicroAppStoreSectionType.other)&&(self.isOverMaxCount() ? (indexPath.section==2) : (indexPath.section==1))
            if sectionType==TCMicroAppStoreSectionType.myApp {//我的应用
                reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headViewId, for: indexPath) as! MicroAppHeadView
                (reusableview as! MicroAppHeadView).lblBigTitle.text="我的应用"
                (reusableview as! MicroAppHeadView).cellType=MicroAppHeadViewType.onlyBig
                (reusableview as! MicroAppHeadView).configHead(params: Dictionary(),dependence: dependenceParam)
                return reusableview
            }else if  sectionType==TCMicroAppStoreSectionType.myAppOverstep {
                reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headViewId, for: indexPath) as! MicroAppHeadView
                (reusableview as! MicroAppHeadView).cellType=MicroAppHeadViewType.myOverSection
                (reusableview as! MicroAppHeadView).configHead(params: ["type":"以上应用在首页展示"],dependence: dependenceParam)
                return reusableview
            }else{
                reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headViewId, for: indexPath) as! MicroAppHeadView
                (reusableview as! MicroAppHeadView).cellType=MicroAppHeadViewType.onlysection
                let dic = (dateSource["group"] as! Array<Any>)[indexPath.section-gap] as! Dictionary<String,Any>
                (reusableview as! MicroAppHeadView).configHead(params: (dic["section"] as? Dictionary<String,Any> ?? Dictionary.init()),dependence: dependenceParam)
                return reusableview
            }
        }else if kind == UICollectionView.elementKindSectionFooter{
            let  isAddFooter:Bool = self.isOverMaxCount() ? (sectionType==TCMicroAppStoreSectionType.myAppOverstep) : (sectionType==TCMicroAppStoreSectionType.myApp)
            if  isAddFooter {
                reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footViewId, for: indexPath) as! MicroAddAppView
                
                (reusableview as! MicroAddAppView).config(param:Dictionary<String,String>.init(), state: myAppState,dependence:dependenceParam,dependencePath: dependencePath)
                (reusableview as! MicroAddAppView).addB = { [unowned self] (str) in
                    self.changEditState()
                }
                
                return reusableview
            }
        }
        return reusableview
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        let sectionType = self.sectionType(section:section)
        //        let isOtherFirst:Bool = (sectionType==TCMicroAppStoreSectionType.other)&&(self.isOverMaxCount() ? (section==2) : (section==1))
        if sectionType==TCMicroAppStoreSectionType.myApp {//我的应用 {
            return CGSize.init(width: ScreenWidth, height: 45)
        }else if  sectionType==TCMicroAppStoreSectionType.myAppOverstep{
            return CGSize.init(width: ScreenWidth, height: 23)
        }//110
        return CGSize.init(width: ScreenWidth, height: 35)
    }
    
    //footer高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        let sectionType = self.sectionType(section:section)
        let  isAddFooter:Bool = self.isOverMaxCount() ? (sectionType==TCMicroAppStoreSectionType.myAppOverstep) : (sectionType==TCMicroAppStoreSectionType.myApp)
        if isAddFooter{
            return CGSize.init(width: ScreenWidth, height: 80)
        }
        return CGSize.init(width: ScreenWidth, height: 0)
    }
    
    //移动相关
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        if myAppState == TCMicroAppStoreState.edit{//编辑状态下my才可以移动
            let sectionType = self.sectionType(section:indexPath.section)
            if sectionType == TCMicroAppStoreSectionType.myApp || sectionType == TCMicroAppStoreSectionType.myAppOverstep {
                return true;
            }
        }
        return false
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        //两种情况 一种跨分区  一种同区
        //交换  1 原始数据交换 2 UI数据交换
        let moveIdx=self.realIndexInarr(index: sourceIndexPath);
        let destinationIdx=self.realIndexInarr(index: destinationIndexPath);
        //my的数据 操作
        if let myArr = (dateSource["my"] as? NSMutableArray){
            let  moveItem:MicroAppModels = myArr [moveIdx] as! MicroAppModels;
            let  destinationItem:MicroAppModels = myArr [destinationIdx] as! MicroAppModels;
            //1原始数据交换
            dataStoreHelper.insertWith(moveItem: moveItem, aimItem: destinationItem, handleArr: self.originMyAppDateArr)
            // 2 UI数据交换
            myArr.removeObject(at: moveIdx)
            myArr.insert(moveItem, at: destinationIdx)
            
        }
        if sourceIndexPath.section != destinationIndexPath.section {
            DispatchQueue.main.asyncAfter(deadline:.now(), execute:{
                self.appCollectionView.reloadSections(NSIndexSet.init(index:0) as IndexSet)
                self.appCollectionView.reloadSections(NSIndexSet.init(index:1) as IndexSet)
            })
        }
    }
    
    func realIndexInarr(index:IndexPath) -> Int {
        let sectionType = self.sectionType(section:index.section)
        if sectionType == TCMicroAppStoreSectionType.myApp {
            return index.row;
        }else{
            return index.row+maxCount;
        }
    }
    
    
    //MARK:-Private-Methods
    func changEditState() {
        if myAppState == TCMicroAppStoreState.edit {
            myAppState=TCMicroAppStoreState.nomal
            appCollectionView.removeGestureRecognizer(longPressGesture)//移除手势
            //存储最新顺序的数据
            dataStoreHelper.myEndEdit(myApps: originMyAppDateArr,allApps: originAllAppDateArr,dataPath: dataPath,dataKey: dataKey, myPath: myDataPath, myKey: myDataKey)
        }else {
            myAppState=TCMicroAppStoreState.edit
            appCollectionView.addGestureRecognizer(longPressGesture)//添加手势
        }
        appCollectionView.reloadData()
    }
    
    func changeShowState()  {
        if myAppState == TCMicroAppStoreState.nomal {
            myAppState=TCMicroAppStoreState.show
        }else{
            myAppState=TCMicroAppStoreState.nomal
        }
        appCollectionView.reloadData()
    }
    
    func openMicroApp(key:String,sourceDic:NSDictionary? = nil)  {
        if addListener {
            let script:JSValue?=self.context.element.eventDictinoary[aClick] as? JSValue
            if script != nil {
                script?.call(withArguments: [sourceDic ?? {}] )
            }
        }else{
            resource.openMicroApp(key, info: ["appKey":key,"transition":"false","microMoreButton":"false","microAppNavBar":"true"], callBack: nil)
            //        resource.open(["appKey":key])
        }
    }
    
    //MARK:-Help methods
    func sectionType(section:Int) -> TCMicroAppStoreSectionType {
        if section==0 {
            return TCMicroAppStoreSectionType.myApp
        }else{
            if self.isOverMaxCount() {
                if section==1{
                    return TCMicroAppStoreSectionType.myAppOverstep
                }
            }
            return TCMicroAppStoreSectionType.other
        }
    }
    
    //my是否超过最大限制
    func isOverMaxCount() -> Bool  {
        if(((dateSource["my"] as? NSMutableArray)?.count ?? 0)>maxCount){
            return true
        }
        return false
    }
    
    func isInMyAPP(model:MicroAppModels) -> Bool {
        let idSer = NSPredicate(format: "appKey=%@", model.appKey ?? "")
        if let arr = (dateSource["my"] as? NSMutableArray)?.filtered(using: idSer) {
            if arr.count > 0 {
                model.isInMy=true
            }else{
                model.isInMy=false
            }
            return arr.count > 0
        }
        return false
    }
    func lock()  {
        DispatchQueue.main.async {
            WindowHUD.shared()?.lock()
        }
    }
    func unlock()  {
        DispatchQueue.main.async {
            WindowHUD.shared()?.unlock()
        }
    }
    
    func synchronizationDate()   {
        let myArr = self.dateSource["my"] as? NSMutableArray ?? []
        let groupArr = self.dateSource["group"] as? NSMutableArray ?? []
        
        if((myArr.count == 0)&&(groupArr.count == 0)){
            self.appCollectionView.isHidden=true;
            errorV.isHidden=true;
            errorV.center=self.center
        }else{
            self.appCollectionView.isHidden=false;
            errorV.isHidden=true;
            
        }
    }
    
    func compilerAllAppList(_ list: [Any]?) {
        guard let r_list = list else {
            return;
        }         // r_list 包含了所有微应用
        //        dataStoreHelper.configGetData(r_list)
        let otherAppArr = NSMutableArray.init()
        let originOtherAppArr = NSMutableArray.init()
        
        for group in r_list{
            
            var otherGroupDic = Dictionary<String,Any>.init()
            var originotherGroupDic = Dictionary<String,Any>.init()
            let groupAppArr=NSMutableArray.init()
            let originGroupAppArr=NSMutableArray.init()
            
            let groupDic = group as? Dictionary<String,Any>
            otherGroupDic["section"] = groupDic?["section"]
            originotherGroupDic["section"] = groupDic?["section"]
            if ((groupDic?["data"]) != nil)  {
                let d_list=groupDic!["data"] as! Array<AnyObject>
                for item in d_list{
                    let  model=MicroAppModels.init()
                    let dic = item as? Dictionary<String,Any>
                    model.configWithParam(params: dic ?? Dictionary<String,Any>.init())
                    let isin = dataStoreHelper.isInStoreOrVersionNotChange(item: dic ??  Dictionary<String,Any>.init())
                    if isin {
                        model.isNeedNewMark=false
                    }else{
                        model.isNeedNewMark=true
                    }
                    
                    //开始服务应用过滤 下架微应用 安卓微应用 excludeList不显示微应用
                    let isSever = dataStoreHelper.filtration(dataDic:dic ??  Dictionary<String,Any>.init())
                    originGroupAppArr.add(model)
                    if !isSever {
                        groupAppArr.add(model)
                    }
                }
            }
            if groupAppArr.count>0 {//如果过滤后还有数据再加到
                otherGroupDic[self.groupApps]=groupAppArr
                otherAppArr.add(otherGroupDic)
            }
            //原始数据加到origin里
            originotherGroupDic[self.groupApps]=originGroupAppArr
            originOtherAppArr.add(originotherGroupDic)
        }
        self.dateSource["group"]=otherAppArr
        self.originAllAppDateArr = originOtherAppArr;//原始数据赋值
        //*************Task*****覆盖
        dataStoreHelper.storeData(r_list);
    }
    
    func compilerOwnerAppList(_ list: [Any]?) {
        guard let r_list = list else {
            return;
        }
        let myAppArr=NSMutableArray.init()
        let originMyAppArr=NSMutableArray.init()
        for item in r_list{
            let  model=MicroAppModels.init()
            let dic = item as? Dictionary<String,Any>
            model.configWithParam(params: dic ?? Dictionary<String,Any>.init())
            let isSever = dataStoreHelper.filtration(dataDic:dic ??  Dictionary<String,Any>.init())
            originMyAppArr.add(model)
            if !isSever {
                myAppArr.add(model)
            }
        }
        self.originMyAppDateArr=originMyAppArr
        self.dateSource["my"]=myAppArr
    }
    
    
    
    func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
    //MARK:-长按事件
    @objc func longPressAction(_ longPress: UILongPressGestureRecognizer){
        let point:CGPoint = longPress.location(in: appCollectionView)
        if let indexPath:IndexPath = appCollectionView.indexPathForItem(at: point){
            let sectionType = self.sectionType(section:indexPath.section)
            if sectionType==TCMicroAppStoreSectionType.myApp || sectionType==TCMicroAppStoreSectionType.myAppOverstep{
                switch longPress.state {
                case .began:
                    //开始移动
                    appCollectionView.beginInteractiveMovementForItem(at: indexPath)
                    break;
                case .changed:
                    appCollectionView.updateInteractiveMovementTargetPosition(point)
                    break;
                case .ended:
                    appCollectionView.endInteractiveMovement()
                    break;
                default:
                    appCollectionView.cancelInteractiveMovement()
                    break;
                }
            }else{
                appCollectionView.cancelInteractiveMovement()
                return;
            }
        }else{
            switch longPress.state {
            case .began:
                break;
            case .changed:
                appCollectionView.updateInteractiveMovementTargetPosition(point)
                break;
            case .ended:
                appCollectionView.cancelInteractiveMovement()
                break;
            default:
                appCollectionView.cancelInteractiveMovement()
                break;
            }
        }
    }
    
    //MARK:-数据从文件读取
    override func loadMvvmAttribute(_ value: Any!, forName name: String!) {
        super.loadMvvmAttribute(value, forName: name)
        if name == "dataPath" {
            dataPath=value as? String ?? ""
            listenCompare()
        }else if name == "dataKey" {
            dataKey=value as? String  ?? ""
            listenCompare()
        }else if name == "excludeList"{
            excludeList =  value as? Array<String> ?? []
            if excludeList.count > 0 {
                dataStoreHelper.excludeList = excludeList
                listenCompare()
            }
        }
        
        if name == "myDataPath" {
            myDataPath=value as? String ?? ""
            listenCompare()
        }else if name == "myDataKey" {
            myDataKey=value as? String  ?? ""
            listenCompare()
        }
    }
    
    func readDataSource() {
        listenCompare()
    }
    
    func readAllValue() {//通过数据模块读取
        //先获取mallApp
        dataStoreHelper.getMallAppData()
        
        //获取allApp,用于过滤掉安卓数据
        dataStoreHelper.getAllAppData()
        
        let obj =  TinyFileManger.sharedInstance().getDataWithPath(dataPath, key: dataKey)
        //            let params:Dictionary = obj as? Dictionary<String, Any> ?? Dictionary.init()
        guard let tempAllApps = obj as? [Dictionary<String, Any>] else {
            return;
        }
        //取缓存的老数据 用于比较标记红点
        dataStoreHelper.getStoreData()
        self.setParam("allApps", value: tempAllApps)
        
        self.appCollectionView.reloadData();
    }
    func readMyValue() {//通过数据模块读取
        //从myApp.json中获取我的数据
        let obj =  TinyFileManger.sharedInstance().getDataWithPath(myDataPath, key: myDataKey)
        //            let params:Dictionary = obj as? Dictionary<String, Any> ?? Dictionary.init()
        guard let tempOwnerApps=obj as? [Dictionary<String, Any>] else{
            return;
        }
        
        self.setParam("ownerApps", value: tempOwnerApps)
    }
    
    func listenCompare(){
        if (dataPath.count>0&&dataKey.count>0){
            self.readAllValue();
        }
        if (myDataPath.count>0&&myDataKey.count>0){
            self.readMyValue();
        }
    }
    
    
    
    func addMicro(model :MicroAppModels)  {
        //1对本地数组的
        model.sourceDic?.setObject(1, forKey: "isAdd" as NSCopying)
        (self.dateSource["my"] as!NSMutableArray).add(model)
        self.originMyAppDateArr.add(model)//原始 数据 添加
        //2任务中心模式下 对UI数据及原始数据修改  点击完成时写入
        writeToAllAppjson(isAdd: 1, appkey: model.appKey ?? "")
    }
    
    func minusMicro(model :MicroAppModels)  {
        //1本地my数组由于要操作index在调用前已经实行
        //2任务中心模式下 对UI数据及原始数据修改  点击完成时写入
        writeToAllAppjson(isAdd: 0, appkey: model.appKey ?? "")
        
    }
    func removeMyOriginItem(key :String)  {
        var  idx = -1;
        for i in 0..<self.originMyAppDateArr.count {
            let aModel:MicroAppModels=self.originMyAppDateArr[i] as! MicroAppModels;
            if aModel.appKey == key {
                idx=i
                break
            }
        }
        if (idx >= 0 ) && (idx < self.originMyAppDateArr.count ){
            self.originMyAppDateArr.removeObject(at: idx)
        }
    }
    
    
    func writeToAllAppjson(isAdd:NSNumber,appkey:String)  {
        var  tempinfo:NSMutableDictionary=NSMutableDictionary.init()
        
        self.changeIsAdd(sourceDicArr: (self.dateSource["group"] as! NSMutableArray), isAdd: isAdd, appkey: appkey)//修改UI数据源
        
        //        tempinfo =
        self.changeIsAdd(sourceDicArr: originAllAppDateArr , isAdd: isAdd ,appkey:appkey);//修改ALL原始数据源
        
        //        let formatAllAppData = dataStoreHelper.prepareForAllAppDataJson(allApp: originAllAppDateArr)
        
        
        //        TinyFileManger.sharedInstance().changeData(withPath: dataPath, data: formatAllAppData, key: "allApp.dataInfos") { (success) in
        //            if success{
        //                //3对首页数据修改（拼装+读取修改）
        //                if isAdd == 1 {//添加  同时需要添加到myApp中
        //                    self.dataStoreHelper.prepareForMyAppDataJson(isAdd: 1, addDic: tempinfo, myApps: nil, myPath:self.myDataPath, myKey:self.myDataKey )
        //                }else if  isAdd == 0{
        //                    self.dataStoreHelper.prepareForMyAppDataJson(isAdd: 0, addDic: nil, myApps: self.originMyAppDateArr,myPath:self.myDataPath, myKey:self.myDataKey)
        //                }
        //            }
        //        }
        
    }
    
    func changeIsAdd(sourceDicArr:NSMutableArray, isAdd:NSNumber,appkey:String) ->NSMutableDictionary {
        var  tempinfo:NSMutableDictionary=NSMutableDictionary.init()
        for i in 0 ..< sourceDicArr.count{
            if let sectionArr = (((sourceDicArr[i] as? Dictionary<String, Any>)?["data"]) as? NSArray){
                var isFind=false;
                for j in 0 ..< sectionArr.count{
                    if let tempDic:NSMutableDictionary = (sectionArr[j] as! MicroAppModels).sourceDic as? NSMutableDictionary{
                        if (tempDic["appKey"] as? String) == appkey{
                            tempDic.setObject(isAdd, forKey: "isAdd" as NSCopying)
                            isFind=true
                            tempinfo = tempDic;
                            break;
                        }
                    }
                }
                if isFind {
                    break
                }
            }
        }
        return tempinfo
    }
    
}
